<route lang="json5">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '优惠券',
  },
}
</route>
<template>
  <div class="container py-6 px-4 box-border bg-[#f7f7f7]">
    <div class="flex justify-between items-center mb-5">
      <div class="text-[16px] text-[#56B756]">本次最大核销优惠卷总额￥{{ useCoupon }}</div>
      <div class="flex items-center" @click="refresh">
        <image src="@/static/images/refresh.png" mode="widthFix" class="w-4"></image>
        <span class="ml-2 text-[#56B756]">刷新</span>
      </div>
    </div>
    <wd-form ref="form" :model="model">
      <wd-cell-group>
        <div class="form-item pb-5 bg-[#f7f7f7]">
          <div class="form-label form-label-required text-[#666] text-[16px]">选择核销金额</div>
          <wd-input
            label=""
            label-width="100px"
            prop="code"
            clearable
            disabled
            custom-input-class="code-input"
            v-model="model.code"
            placeholder="请选择核销的优惠券"
            :rules="[{ required: true, message: '请选择核销的优惠券' }]"
          />
        </div>
      </wd-cell-group>
    </wd-form>
    <div class="use-boxs text-[14px]">
      <div
        class="use-item flex items-center justify-between"
        v-for="(item, index) in list"
        :key="index"
      >
        <div class="data-left flex justify-between">
          <div class="price text-[#56B756]">￥{{ item.amount }}</div>
          <div class="flex text-[#999]">
            <div class="text-[#666]">有效期</div>
            <div class="date ml-2">
              {{ item.useStart_time }}
              <span class="px-1 text-[#666]">至</span>
              {{ item.useEnd_time }}
            </div>
          </div>
        </div>
        <image
          v-if="item.checked"
          src="@/static/images/check-fill.png"
          mode="widthFix"
          class="w-[18px]"
          @click="handleCheck(item)"
        ></image>
        <image
          v-else
          src="@/static/images/check-fill-gray.png"
          mode="widthFix"
          class="w-[18px]"
          @click="handleCheck(item)"
        ></image>
      </div>
    </div>
    <wd-action-sheet v-model="show">
      <div class="qrcode-content">
        <div class="text-[#6BB748] text-[20px]">￥{{ selectAmount }}</div>
        <!--        <image src="@/static/images/qrcode.png" mode="widthFix" class="w-[150px]"></image>-->
        <!--        <VueQrcode :value="model.code" :width="150" />-->
<!--        <canvas ref="qrcode" id="qrcode" canvas-id="qrcode" style="width: 150px; height: 150px"></canvas>-->
        <TkiQrcode ref="qrcode" :onval="true" :val="qrcodeValue" :unit="'px'" :size="150"></TkiQrcode>
      </div>
    </wd-action-sheet>
    <buttonBtn @btnClick="confirmUse" v-if="!show">
      <view>确认使用</view>
    </buttonBtn>
  </div>
</template>

<script setup lang="ts">
import { checkCoupon, myCoupon } from '@/service/user'
import { useToast } from 'wot-design-uni'
import TkiQrcode from 'tki-qrcode/components/tki-qrcode/tki-qrcode.vue'
const model = reactive<{
  // 优惠券
  code: string
}>({
  code: '',
})
const form = ref()

function handleSubmit() {
  // console.log(form.value);

  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

function handleCheck(item: ICoupon) {
  const amount = `${list.value.reduce((total: number, item: ICoupon) => {
    if (item.checked) {
      total += parseFloat(item.amount)
    }
    return total
  }, 0)}`
  console.log(amount, 'amount')
  if (parseFloat(amount) + parseFloat(item.amount) > parseFloat(useCoupon.value) && !item.checked) {
    toast.show('核销金额不能超过最大核销金额')
  } else {
    item.checked = !item.checked
    model.code = `${item.checked ? parseFloat(amount) + parseFloat(item.amount) : parseFloat(amount) - parseFloat(item.amount)}`
  }
}
const toast = useToast()
const list = ref<ICoupon[]>([])
const selectAmount = computed(() => {
  return list.value.reduce((total: number, item: ICoupon) => {
    if (item.checked) {
      total += parseFloat(item.amount)
    }
    return total
  }, 0)
})
const total = ref<number>(0) // 总金额
// eslint-disable-next-line camelcase
const useCoupon = ref<string>('') // 最大核销金额
const getList = async () => {
  const res: IResData<IPageCouponRes<ICoupon>> = await myCoupon()
  if (res.code === 1) {
    total.value = res.data?.total || 0
    // eslint-disable-next-line camelcase
    useCoupon.value = res.data?.use_coupon || '0'
    list.value = res.data.data.map((item: ICoupon) => {
      return {
        ...item,
        checked: false,
      }
    })
  } else {
    toast.show(res.msg)
  }
}
const show = ref(false)
const qrcodeValue = ref('')
const qrcode = ref()
const confirmUse = async () => {
  if (!list.value.some((item: ICoupon) => item.checked)) {
    return toast.show('请选择优惠券')
  }
  qrcodeValue.value = JSON.stringify(
    list.value.filter((item: ICoupon) => item.checked).map((item: ICoupon) => item.id),
  )
  // qrcode.value._makeCode()
  show.value = true
  // const haveChecked = list.value.some((item: ICoupon) => item.checked)
  // const res: IResData<IPageCouponRes<ICoupon>> = await checkCoupon(id)
  // if (res.code === 1) {
  //   // toast.show('核销成功')
  //   show.value = true
  //   await getList()
  // } else {
  //   toast.show(res.msg)
  // }
}
onLoad(async () => {
  await getList()
})
async function refresh() {
  await getList()
  toast.success('刷新成功')
}
</script>
<style scoped>
.container {
  min-height: 100vh;
  padding-bottom: 64px;
}
.form-label {
  margin-bottom: 20rpx;
}
.form-label-required {
  position: relative;
  padding-left: 8px;
}
.form-label-required::before {
  content: '*';
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 12px;
  color: #f61515;
}
:deep(.wd-input) {
  border-radius: 16rpx !important;
}
.use {
  width: 134rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 8rpx;
}
.use-title {
  text-align: right;
}

.use-item {
  gap: 28rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
  width: 100%;
  border-radius: 10px;
  background: #ffffff;
  box-sizing: border-box;
}

.data-left {
  gap: 20rpx;
  flex-direction: column;
}

.icon {
  vertical-align: inherit;
}

.watch-white {
  width: 22px;
  height: 22px;
  margin-right: 6px;
}

:deep(.code-input) {
  height: 112rpx !important;
  padding: 0 16rpx !important;
}
:deep(.wd-input.is-disabled .wd-input__inner) {
  color: black !important;
}
.qrcode-content {
  display: flex;
  gap: 74rpx;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-top: 168rpx;
  padding-bottom: 220rpx;
}
</style>
